package com.ltu.config.initiallydata;


import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import com.ltu.config.WxMaProperties;
import com.ltu.domain.mp_entity.customize.CompanyEntity;
import com.ltu.service.customize.CompanyService;
import com.wechat.pay.java.core.RSAAutoCertificateConfig;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.api.impl.WxMaServiceImpl;
import cn.binarywang.wx.miniapp.config.impl.WxMaDefaultConfigImpl;
import me.chanjar.weixin.common.error.WxRuntimeException;


@Order(999)
@Component
public class InitiallyData  implements  CommandLineRunner {
	@Autowired
	private  CompanyService  companyService;
	@Resource
	private  ApplicationContext applicationContext;
	public final static  String RSAAutoCertificateKey = "rSAAutoCertificate";
	
	@Override
	 public void run(String... args) throws Exception {
		
	
		 //将applicationContext转换为ConfigurableApplicationContext
        ConfigurableApplicationContext configurableApplicationContext = (ConfigurableApplicationContext) applicationContext;
        //获取BeanFactory
        DefaultListableBeanFactory defaultListableBeanFactory = (DefaultListableBeanFactory) configurableApplicationContext.getAutowireCapableBeanFactory();
        rSAAutoCertificateConfig(defaultListableBeanFactory);
        
	}
	
	private void rSAAutoCertificateConfig( DefaultListableBeanFactory defaultListableBeanFactory) {
		List<CompanyEntity> datas = companyService.list();
    	Map<String, List<CompanyEntity>> maps = datas.stream().collect(Collectors.groupingBy( CompanyEntity :: getMchId));
		for (String key : maps.keySet()) {
			CompanyEntity company = maps.get(key).get(0);
			String rootPath = System.getProperties().getProperty("user.dir").concat(File.separator).concat("cert");
//			String certPemPath = rootPath.concat(File.separator).concat("apiclient_cert.pem");
			String keyPemPath = rootPath.concat(File.separator).concat(company.getMchId().concat("_key").concat(".pem"));
			RSAAutoCertificateConfig config = new RSAAutoCertificateConfig.Builder()
									.merchantId(company.getMchId())
									.privateKeyFromPath(keyPemPath)
									.merchantSerialNumber(company.getCertSerialNo())
									.apiV3Key(company.getMchKeyApi3())
									.build();
			  //动态注册证书
	        defaultListableBeanFactory.registerSingleton(RSAAutoCertificateKey.concat(company.getMchId()),config);
	       
		}
		
	}
	
	

	
	
	
}
